'use client';

import './style.scss';
import { useState, useEffect } from 'react';
import { useParams } from 'next/navigation';
import { fetchApi } from '@/lib/utils/client';

type ConsentInfo = {
	crewSessionID: number;
	title: string;
	crewName: string;
	isConsented: boolean;
	crewMemberID: number;
};

export default function CrewConsentPage()
{
	const { sessionID } = useParams<{ sessionID: string }>();
	const [info, setInfo] = useState<ConsentInfo|null>(null);
	const [loading, setLoading] = useState(true);
	const [agreed, setAgreed] = useState(false);
	const [submitting, setSubmitting] = useState(false);
	const [done, setDone] = useState(false);

	useEffect(() => {
		fetchApi<ConsentInfo>(`/api/crew/consent/info/${sessionID}`)
			.then(res => {
				const data = res.data;
				setInfo(data ?? null);
				if (data?.isConsented) setDone(true);
			})
			.catch(() => {})
			.finally(() => setLoading(false));
	}, [sessionID]);

	const handleConsent = async () => {
		if (!info || !agreed) return;
		setSubmitting(true);
		try {
			await fetchApi('/api/crew/session/consent', {
				method: 'POST',
				body: {
					crewSessionID: info.crewSessionID,
					crewMemberID: info.crewMemberID
				}
			});
			setDone(true);
		} catch (err: unknown) {
			alert(err instanceof Error ? err.message : '동의 처리에 실패했습니다.');
		} finally {
			setSubmitting(false);
		}
	};

	if (loading) return <div className="crew-consent"><p>준비 중...</p></div>;
	if (!info) return <div className="crew-consent"><p>세션 정보를 찾을 수 없습니다.</p></div>;

	return (
		<div className="crew-consent">
			<h1 className="crew-consent__title">크루 방송 참여 동의</h1>
			<p className="crew-consent__subtitle">크루장이 방송 참여를 요청했습니다</p>

			<div className="crew-consent__info">
				<div className="crew-consent__row">
					<span className="crew-consent__row-label">크루</span>
					<span className="crew-consent__row-value">{info.crewName}</span>
				</div>
				<div className="crew-consent__row">
					<span className="crew-consent__row-label">방송 제목</span>
					<span className="crew-consent__row-value">{info.title}</span>
				</div>
			</div>

			{done ? (
				<div className="crew-consent__done">✓ 동의가 완료되었습니다. 전원 동의 시 방송이 시작됩니다.</div>
			) : (
				<>
					<div className="crew-consent__check">
						<input type="checkbox" id="agree" checked={agreed} onChange={e => setAgreed(e.target.checked)} />
						<label htmlFor="agree">크루 방송 참여에 동의합니다</label>
					</div>
					<button
						type="button"
						className="studio-page__btn studio-page__btn--primary"
						onClick={handleConsent}
						disabled={!agreed || submitting}
					>
						{submitting ? '처리 중...' : '동의하기'}
					</button>
				</>
			)}
		</div>
	);
}